package middleware

import (
	"fmt"
	"gitee.com/z930255076/go-ext/log"
	"gitee.com/z930255076/go-ext/utils"
	"github.com/gofiber/fiber/v2"
	"os"
	"strconv"
	"time"
)

func Slow(c *fiber.Ctx) error {
	// 前置中间件
	start := time.Now()
	utils.TE.RequestBegin()

	err := c.Next()

	// 后置中间件
	if err != nil {
		return err
	}

	end := time.Now()
	latency := end.Sub(start)

	slowTime, _ := strconv.Atoi(os.Getenv("REQUEST_SLOW_TIME"))
	if slowTime <= 0 {
		slowTime = 5
	}

	if int(latency.Seconds()) >= slowTime {
		msg := fmt.Sprintf("execute %s %s", latency.String(), c.Path())
		log.SlowLogger()
		log.SlowPrefixLogger(msg, "REQUEST")
	}

	return nil
}
